package com.eco.fanliapp.job.hdkitemjob;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.ApiUtils;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.JsonUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 今日爆款
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class KingKongTodayHotTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(KingKongTodayHotTask.class);

    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private ISyLabelGoodsService iSyLabelGoodsService;

    @Autowired
    private IUserCashschemeService userCashschemeService;


    public KingKongTodayHotTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执获取今日爆款商品定时任务-KingKongTodayHotTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

//        long min_hot = 1;
        AppCompany com = userCashschemeService.findCompanyAll();

        List<String> list = iSyLabelGoodsService.findByLabelCode("2");
        if (list.size() > 0) {
            appGoodsMapper.updateGoodsTopByIdList(list, "1");
        }
        iSyLabelGoodsService.deleteByLableCode("2");
        int intArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 0};
        for (int y = 0; y < intArray.length; y++) {
            long min_hot = 1;
            while (true) {
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("cid", intArray[y]);
                data.put("item_type", 1);
                data.put("sale_type", 2);
                data.put("min_id", min_hot);
                try {

                    //前往好单库拉取商品
                    String str = ApiUtils.getData(ApiEnum.SALES_LIST, data);

                    //log.info("获取的入库数据{}",str);
                    JSONObject object = JSONObject.parseObject(str);
                    AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
                    if (response != null && response.getCode() == 1) {//code等于1代表请求成功
                        JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
                        List<AppGoods> bean = JsonUtils.getJsonToList(array.toJSONString(), AppGoods.class);

                        if (bean == null || bean.size() <= 0) {
                            break;
                        }

                        for (AppGoods dataBean : bean) {
                            if (dataBean.getFqcat() != null) {

                                if ("5".equals(dataBean.getFqcat())) {
                                    dataBean.setFqcat("3");
                                }
                                if ("7".equals(dataBean.getFqcat())) {
                                    dataBean.setFqcat("6");
                                }
                                if ("13".equals(dataBean.getFqcat())) {
                                    dataBean.setFqcat("12");
                                }
                                if ("16".equals(dataBean.getFqcat())) {
                                    dataBean.setFqcat("15");
                                }
                                if ("8".equals(dataBean.getFqcat())) {
                                    dataBean.setFqcat("9");
                                }

                                if (intArray[y] == 0) {
                                    dataBean.setRecommend(1);
                                }
                            }

                            if (dataBean.getCouponstarttime() != null
                                    && dataBean.getCouponendtime() != null
                                    && dataBean.getEndTime() != null) {
                                dataBean.setCouponstarttime(
                                        dataBean.getCouponstarttime() == null ? "0" :
                                                dataBean.getCouponstarttime() + "000");
                                dataBean.setCouponendtime(
                                        dataBean.getCouponendtime() == null ? "0" :
                                                dataBean.getCouponendtime() + "000");
                                dataBean.setStartTime(
                                        dataBean.getStartTime() == null ? "0" :
                                                dataBean.getStartTime() + "000");
                                dataBean.setEndTime(
                                        dataBean.getEndTime() == null ? "0" :
                                                dataBean.getEndTime() + "000");
                                dataBean.setStarttime(
                                        dataBean.getStarttime() == null ? "0" :
                                                dataBean.getStarttime() + "000");
                                dataBean.setTaobaoImage(dataBean.getTaobaoImage() == null ? dataBean.getItempic() : dataBean.getTaobaoImage().replace(" ", ""));

                                dataBean = appGoodsService.getMoneyInfoByGoodsId(com, dataBean);

                                //判断是否最终金额小于0
                                BigDecimal itemendprice = new BigDecimal(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                                BigDecimal tkMoney = new BigDecimal(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney());
                                if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                                    continue;
                                }
                                dataBean.setItemTop(6);
                                dataBean.setCreateTime(DateUtils.getNowTimestamp());
                                dataBean.setUpdateTime(DateUtils.getNowTimestamp());
                                dataBean.setAddUserId(-113);

                                List<AppGoods> appGoods = appGoodsService.selectAppGoodsByItemId(Long.parseLong(dataBean.getItemid()));
                                if (appGoods == null || appGoods.size() == 0) {
                                    int i = appGoodsService.insertAppGoods(dataBean);
                                }

                                SyLabelGoods syLabelGoods = new SyLabelGoods();
                                syLabelGoods.setItemId(dataBean.getItemid());
                                syLabelGoods.setLabelCode("2");
                                syLabelGoods.setLabelTypeId("3");
                                syLabelGoods.setDeleted(0);

                                int i = iSyLabelGoodsService.addSyLabelGoods(syLabelGoods);
                                if (i > 0) {
                                    log.info("标签添加成功");
                                } else {
                                    log.info("标签添加失败");
                                }
                            }
                        }
                    } else {
                        log.info("拉取今日爆款商品API   请求失败{}", response.getMsg());
                        break;
                    }
                    min_hot = response.getMinId();
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("获取今日爆款商品定时任务错误");
                    break;
                }
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束获取今日爆款商品定时任务-KingKongTodayHotTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - beginTime));

    }
}
